package de.gzork.zmpp;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.zmpp.ExecutionControl;
import org.zmpp.windowing.AnnotatedText;
import org.zmpp.windowing.BufferedScreenModel;

public class ZmppWrapper {
	private Logger LOGGER = Logger.getAnonymousLogger();
	private BufferedScreenModel screenModel;
	private ExecutionControl executionControl;
	
	public ZmppWrapper(BufferedScreenModel screenModel, ExecutionControl executionControl) {
		this.screenModel = screenModel;
		this.executionControl = executionControl;
	}

	public String execute(String command) {
		int pc = executionControl.getMachine().getPC();
				
		String result = "";
		try {
			executionControl.resumeWithInput(new String("restore".getBytes(), "UTF-8"));
			screenModel.reset();
			executionControl.resumeWithInput(new String(command.getBytes(), "UTF-8"));
			for (AnnotatedText text : screenModel.getLowerBuffer()) {
				result += text.getText().trim().replaceAll(">", "");
			}
			executionControl.resumeWithInput(new String("save".getBytes(), "UTF-8"));
			screenModel.reset();
			
		} catch (UnsupportedEncodingException e) {
			LOGGER.log(Level.WARNING, e.getMessage());
			return null;
		}

		return result;
	}
}
